package com.vsked.io;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import com.vsked.bean.ConnectionInfo;
import com.vsked.classMssqls.MssqlSon;
import com.vsked.connection.ConnectionUtil;
import com.vsked.database.ColumnInfo;
import com.vsked.database.TableInfo;
import com.vsked.util.BeanProcess;
import com.vsked.util.Symbol;
import com.vsked.util.TransFormDataType;

public class WriteToFile {
	
	public static void saveFile(String str,String inPath)
	{
			String fpath = inPath;			
			try {
				File f = new File(fpath);
				FileWriter fw = new FileWriter(f,true);
				fw.write(str);
				fw.close();				
		    }
		    catch (Exception e) {
		    	e.printStackTrace();
		    }			
	}//end save file
	
	public static String saveBeanFile(ConnectionInfo ci,String inPath) throws Exception{
		String beanStrAll="";
		Connection conn = new ConnectionUtil().getSqlServer2000Connection(ci);
        TableInfo tableInfo=new TableInfo();
        ColumnInfo columnInfo=new ColumnInfo();
		List<String> tableName = tableInfo.getSqlServerTableName(ci);
		Set tableNameSets = new HashSet<String>();
		for (int tableIndex = 0; tableIndex < tableName.size(); tableIndex++) {
			beanStrAll="";
			String tempTableName=Symbol.getStringFirstUpperCase(tableName.get(tableIndex)) ;
			//System.out.println(tempTableName);
			String beanDeclareStr="";
			String beanSetterAndGetter="";
			List<Map> columnName=columnInfo.getTableColumnNameAndDataType(ci, tableName.get(tableIndex));
			for(int columnIndex=0;columnIndex<columnName.size();columnIndex++){
				Map columnMap=columnName.get(columnIndex);
				Iterator it=columnMap.entrySet().iterator();
				while(it.hasNext()){
					Map.Entry me=(Map.Entry)it.next();
					String columnNameStr=Symbol.replaceSymbol(me.getKey().toString());
					String inColumn=columnNameStr;
					String inColumnDataType=TransFormDataType.getSqlServerDataType(Integer.parseInt(me.getValue().toString()));
					System.out.println(inColumn+"|"+inColumnDataType);
					beanDeclareStr+=BeanProcess.getFieldDeclare(inColumn,inColumnDataType);
					beanSetterAndGetter+=BeanProcess.getFieldGetterMethod(inColumn,inColumnDataType);
					beanSetterAndGetter+=BeanProcess.getFieldSetterMethod(inColumn, inColumnDataType);
				}
			}//end columnIndex
			beanStrAll=BeanProcess.getClassForObject(tempTableName,beanDeclareStr+beanSetterAndGetter);
			System.out.println(beanStrAll);
			//saveFile(beanStrAll,inPath+tempTableName+".java");
		}// end for tableIndex
		return beanStrAll;
	}
}
